﻿using UnityEngine;

/// <summary>
/// 为每个物体分配不同的材质属性 -- 适配SPR批处理
/// </summary>
[DisallowMultipleComponent]
public class PerObjectMaterialProperties : MonoBehaviour {
	
    static int baseColorId = Shader.PropertyToID("_BaseColor"); // 颜色
    static int cutoffId = Shader.PropertyToID("_Cutoff"); // alpha裁剪
    static int metallicId = Shader.PropertyToID("_Metallic"); // 金属感
    static int smoothnessId = Shader.PropertyToID("_Smoothness"); // 光滑度
	
    [SerializeField]
    Color baseColor = Color.white;
    
    [SerializeField, Range(0f, 1f)]
    float cutoff = 0.5f, metallic = 0f, smoothness = 0.5f;
    
    static MaterialPropertyBlock block;
    
    void Awake () {
	    OnValidate();
    }
    
    // 激活时调用
    void OnValidate () 
    {
	    if (block == null) {
		    block = new MaterialPropertyBlock();
	    }
	    block.SetColor(baseColorId, baseColor);
	    block.SetFloat(cutoffId, cutoff);
	    block.SetFloat(metallicId, metallic);
	    block.SetFloat(smoothnessId, smoothness);
	    GetComponent<Renderer>().SetPropertyBlock(block);
    }
}